package com.peng.leetcode.tree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * RightSideView1
 * 199. 二叉树的右视图
 * https://leetcode.cn/problems/binary-tree-right-side-view/
 * <p>
 * Created on 2022/11/20
 *
 * @author lupeng
 */
public class RightSideView1 {

    /**
     * 二叉树的右视图，使用层级遍历
     * 进入while循环时根据队列长度循环，最后一个就是这一层级的最右节点
     */
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode n = q.poll();
                if (i == size - 1) {
                    result.add(n.val);
                }
                if (n.left != null) {
                    q.offer(n.left);
                }
                if (n.right != null) {
                    q.offer(n.right);
                }
            }
        }
        return result;
    }
}
